package com.sinaapp.gavinzhang.GSpider.http;

import com.sinaapp.gavinzhang.GSpider.common.IpUtil;
import com.sinaapp.gavinzhang.GSpider.common.ServletUtil;
import com.sinaapp.gavinzhang.GSpider.http.annotation.ServletClass;
import com.sinaapp.gavinzhang.GSpider.http.servlet.ConfigServlet;
import com.sinaapp.gavinzhang.GSpider.management.RegistrationCenter;
import com.sinaapp.gavinzhang.GSpider.management.Stub;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.component.Container;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Servlet;

/**
 * @author gavin
 * @version 1.0
 * @date 2015/9/29
 * @description 配置状态管理器网页版
 */
public class HttpServer {

    private static final Logger logger = LoggerFactory.getLogger(HttpServer.class);

    public static final int DEFAULT_PORT = 8080;

    public final static Stub webStub = Stub.newStub();
    public static int port;

    private boolean shutdown = false;

    public HttpServer() {
    }

    public static void setUp() throws Exception {
        logger.warn("注册中心IP为:(默认)" + IpUtil.getRealIp());
        setUp(IpUtil.getRealIp());
    }

    public static void setUp(String ip)throws Exception{
        logger.warn("注册中心端口号为:(默认)" + RegistrationCenter.DEFAULT_PORT);
        setUp(ip, RegistrationCenter.DEFAULT_PORT,HttpServer.DEFAULT_PORT);
    }

    public static void setUp(int localPort) throws Exception {
        logger.warn("注册中心IP为:(默认)" + IpUtil.getRealIp());
        logger.warn("注册中心端口号为:(默认)" + RegistrationCenter.DEFAULT_PORT);
        setUp(IpUtil.getRealIp(),RegistrationCenter.DEFAULT_PORT,localPort);
    }

    public static void setUp(String ip, int port) throws Exception {
        logger.warn("配置状态管理器端口号为:(默认)" + HttpServer.DEFAULT_PORT);
        setUp(ip, port, HttpServer.DEFAULT_PORT);
    }

    public static void setUp(String ip,int port ,int localPort)throws Exception{
        logger.info("注册中心IP为:"+ip);
        logger.info("注册中心端口号为:"+port);
        logger.info("配置状态管理器端口号为:"+localPort);
        ConfigServlet.centerIp = ip;
        ConfigServlet.centerPort = port;
        HttpServer.port = localPort;


        Server server = new Server(HttpServer.port);

        ServletContextHandler context = new ServletContextHandler(
                ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        logger.info("GServer 启动中...");
        ServletUtil.addServlet(context, "com.sinaapp.gavinzhang.GSpider.http.servlet");
        logger.info("GServer 添加RPC配置状态管理服务成功!");
        server.start();
        logger.info("GServer 地址: " + server.getURI().toString());
        logger.info("GServer 启动成功!" + server.getState());
    }

    public static void main(String[] args) throws Exception {
        setUp();
    }

}
